package com.dtdream.emr;

import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

import java.util.Arrays;
import java.util.Iterator;

public final class SplitPart extends UDF {

    public String evaluate(String source, String pattern, int startp) {
        String ret = "";

        if (null == source || "" == source || null == pattern || 0 >= startp) {
            return ret;
        }

        String[] result = source.split(pattern);

        if (result.length > startp - 1) {
            ret = ret + result[startp - 1];
        }

        return ret;
    }

    public String evaluate(String source, String pattern, int startp, int endp) {
        String ret = "";

        if (null == source || "" == source || null == pattern || 0 >= startp || endp < startp) {
            return ret;
        }
        String[] result = source.split(pattern);

        if (result.length > startp - 1) {
            StringBuilder buf = new StringBuilder(source.length());
            int start = startp - 1;
            int end  = (result.length  > endp) ?  endp : result.length;
            for (int i = start; i < end; i++) {
                if (i > start){
                    buf.append(pattern);
                }
                buf.append(result[i]);
            }
            ret = buf.toString();
        }

        return ret;
    }
}

